<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <div class="mb-10px">
      <ElButton type="primary" @click="action('add')">新增</ElButton>
      <ElButton :loading="delLoading" type="danger" @click="delData()"> 批量删除 </ElButton>
    </div>

    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :border="true"
      :pagination="{
        total: tableObject.count
      }"
      @register="register"
    >
      <template #action="{ row }">
        <ElButton type="primary" @click="action('edit', row)" title="编辑"> 编辑 </ElButton>
        <ElButton type="warning" @click="action('password', row)" title="修改密码">
          修改密码
        </ElButton>
        <ElButton type="success" @click="action('see', row)" title="详情"> 详情 </ElButton>
        <ElButton type="danger" @click="action('del', row)" title="删除"> 删除 </ElButton>
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Add
      v-if="actionType == 'add'"
      ref="editRef"
      :form-schema="allSchemas.formSchema"
      :current-row="tableObject.currentRow"
    />

    <Edit v-if="actionType == 'edit'" ref="editRef" :current-row="tableObject.currentRow" />

    <See
      v-if="actionType == 'see'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
    />

    <template #footer>
      <ElButton v-if="actionType !== 'see'" type="primary" :loading="loading" @click="save()">
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { ElButton, ElMessageBox, ElMessage } from 'element-plus'

import { Table } from '@/components/Table'
import {
  ucUserAddAdminApi,
  ucUserBatchDelAdminApi,
  ucUserDelAdminApi,
  ucUserEditAdminApi,
  ucUserListAdminApi,
  ucUserEditPasswordAdminApi
} from '@/api/uc/user'
import { useTable } from '@/hooks/web/useTableTest'
import { TableData } from '@/api/uc/user/types'
import { ref, unref, reactive } from 'vue'
import Add from './components/Add.vue'
import Edit from './components/Edit.vue'
import See from './components/See.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
// 获取字典
// import { useCache } from '@/hooks/web/useCache'
// const { wsCache } = useCache()
// const dict: any = wsCache.get('dict')
// 字典通过value获取label
// const getDictLabel = (type, value) => {
//   let data = dict[type].find((item) => {
//     return item.value == value
//   })
//   return data ? data.label : ''
// }
const { register, tableObject, methods } = useTable<
  {
    total: number
    list: TableData[]
  },
  TableData
>({
  getListApi: ucUserListAdminApi,
  response: {
    data: 'data',
    count: 'count'
  }
})

const { getList, setSearchParams } = methods

getList()

const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'user_id',
    label: '主键',
    fixed: 'left',
    width: 60,
    table: {
      show: true
    },
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'username',
    label: '用户名',
    width: 100,
    search: {
      show: true
    }
  },
  {
    field: 'nickname',
    label: '姓名',
    fixed: 'left',
    width: 100,
    search: {
      show: true
    }
  },
  {
    field: 'email',
    label: '电子邮箱',
    width: 150,
    search: {
      show: true
    }
  },
  {
    field: 'mobile',
    label: '手机号',
    width: 150,
    search: {
      show: true
    }
  },
  // {
  //   field: 'birthday',
  //   label: '生日',
  //   width: 120,
  //   search: {
  //     show: true
  //   },
  //   form: {
  //     component: 'DatePicker',
  //     componentProps: {
  //       type: 'date',
  //       valueFormat: 'YYYY-MM-DD'
  //     }
  //   }
  // },
  // {
  //   field: 'gender',
  //   label: '性别',
  //   width: 60,
  //   formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
  //     return cellValue != '0' ? getDictLabel('user_sex', cellValue) : ' '
  //   },
  //   form: {
  //     component: 'Select',
  //     componentProps: {
  //       options: dict.user_sex
  //     }
  //   },
  //   search: {
  //     component: 'Select',
  //     componentProps: {
  //       options: dict.user_sex
  //     },
  //     show: true
  //   }
  // },
  // {
  //   field: 'is_stop',
  //   label: '是否停用',
  //   width: 80,
  //   formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
  //     return h(
  //       ElTag,
  //       {
  //         type: cellValue == '0' ? 'success' : cellValue == '1' ? 'warning' : 'danger'
  //       },
  //       () => (cellValue == '0' ? '启用' : cellValue == '1' ? '停用' : '未知')
  //     )
  //   },
  //   form: {
  //     component: 'Select',
  //     componentProps: {
  //       options: [
  //         {
  //           label: '启用',
  //           value: '0'
  //         },
  //         {
  //           label: '停用',
  //           value: '1'
  //         }
  //       ]
  //     }
  //   }
  // },
  {
    field: 'create_time',
    label: '创建时间',
    width: 170,
    form: {
      show: false,
      component: 'DatePicker',
      componentProps: {
        disabled: true,
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    }
  },
  {
    field: 'update_time',
    label: '修改时间',
    width: 170,
    form: {
      show: false,
      component: 'DatePicker',
      componentProps: {
        disabled: true,
        type: 'datetime',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    }
  },
  {
    field: 'action',
    width: 340,
    fixed: 'right',
    label: t('tableDemo.action'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)

const dialogTitle = ref('')

const delLoading = ref(false)

const delData = async () => {
  const { getSelections } = methods
  const selections = await getSelections()
  const ids = selections.map((v) => v.user_id)
  delLoading.value = true
  ElMessageBox.confirm(t('common.delMessage'), t('common.delWarning'), {
    confirmButtonText: t('common.delOk'),
    cancelButtonText: t('common.delCancel'),
    type: 'warning'
  })
    .then(async () => {
      let res = await ucUserBatchDelAdminApi({ ids: ids })
        .catch(() => {})
        .finally(() => {
          delLoading.value = false
        })
      if (res) {
        getList()
      }
    })
    .catch(() => {})
}

const actionType = ref('')

const action = async (type: string, row: TableData = {}) => {
  actionType.value = type
  switch (type) {
    case 'edit':
      dialogTitle.value = '编辑'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'password':
      ElMessageBox.prompt('请填写需要修改的密码', '修改密码', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        inputType: 'password'
        // inputErrorMessage: 'Invalid Email'
      })
        // ElMessageBox.confirm('确定要删除这个角色吗？', '删除', {
        //   confirmButtonText: '确认',
        //   cancelButtonText: '取消',
        //   type: 'warning'
        // })
        .then(async ({ value }) => {
          let res: any = await ucUserEditPasswordAdminApi({
            user_id: row.user_id,
            password: value
          }).catch(() => {})
          if (res) {
            ElMessage({
              type: 'success',
              message: res.msg
            })
          }
        })
        .catch(() => {
          console.log('这里是取消confirm弹框')
        })
      break
    case 'add':
      dialogTitle.value = '新增'
      tableObject.currentRow = {
        is_stop: '0',
        gender: '1'
      }
      dialogVisible.value = true
      break
    case 'see':
      dialogTitle.value = '查看'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'del':
      ElMessageBox.confirm('确定要删除这个角色吗？', '删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          apiDel(row.user_id)
        })
        .catch(() => {
          console.log('这里是取消confirm弹框')
        })
      break
    default:
      console.log('未知类型')
  }
}

const apiDel = async (user_id) => {
  let delRes = await ucUserDelAdminApi({ user_id: user_id })
    .catch(() => {})
    .finally(() => {
      loading.value = false
    })
  if (delRes) {
    getList()
  }
}

const editRef = ref<ComponentRef<typeof Edit>>()

const loading = ref(false)

const save = async () => {
  const edit = unref(editRef)
  switch (actionType.value) {
    case 'edit':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          loading.value = true
          const data = (await edit?.getFormData()) as TableData
          let res: any = await ucUserEditAdminApi(data)
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            ElMessage({
              type: 'success',
              message: res.msg
            })
            getList()
          }
        }
      })

      break
    case 'add':
      await edit?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          loading.value = true
          const data = (await edit?.getFormData()) as TableData
          let res: any = await ucUserAddAdminApi(data)
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            ElMessage({
              type: 'success',
              message: res.msg
            })
            getList()
          }
        }
      })
      break
    default:
      console.log('未知类型')
  }
}
</script>
